﻿using Reticulum.User;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Reticulum.Communication
{
    public partial class UserFrom : Form
    {
        public UserFrom()
        {
            InitializeComponent();
        }//转移
        

        public Socket clientsocket { get; set; }//转移

        public void ReceiveDate(object socket)
        {
            var proxSocket = socket as Socket;
            byte[] data = new byte[1024 * 1024];
            while (true)
            {
                int len = 0;
                try
                {
                    len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None);
                }
                catch (Exception ex)
                {
                    //异常退出
                    AppendTextTolog(string.Format("服务器端：{0}非常退出", proxSocket.RemoteEndPoint.ToString()));

                    StopContent();//关闭连接

                    return;//让方法结束,终结当前客户端数据的异步线程
                }
                if (len <= 0)
                {
                    //客户端正常退出
                    AppendTextTolog(string.Format("服务器端：{0}正常退出", proxSocket.RemoteEndPoint.ToString()));
                    StopContent();//停止连接

                    return;//让方法结束,终结当前客户端数据的异步线程
                }
                //把接收到的数据放到文本框上去
                string str = Encoding.Default.GetString(data, 0, len);
                AppendTextTolog(str);
                AppendTextTolog(string.Format("接收到客户端：{0}的信息是：{1}", proxSocket.RemoteEndPoint.ToString(), str));
            }
        }//

        private void StopContent()
        {
            try
            {
                if (clientsocket.Connected)
                {
                    clientsocket.Shutdown(SocketShutdown.Both);
                    clientsocket.Close(100);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }//

        public void AppendTextTolog(string tex)
        {
            //Action<string> sdel = a =>{ };

            //sdel = new Action<string>(a => { });

            ////sdel+=
            //sdel("sss");
            //sdel.Invoke("sss");
            //sdel.BeginInvoke("sss", null, null);


            if (texlog.InvokeRequired)
            {
                texlog.BeginInvoke(new Action<string>(s =>
                {
                    this.texlog.Text = string.Format("{0}\r\n{1}", s, texlog.Text);
                }), tex);
                //同步方法。
                //texlog.Invoke(new Action<string>(s =>
                //{
                //    this.texlog.Text = string.Format("{0}\r\n{1}",s,texlog.Text);
                //}), tex);
            }
            else
            {
                this.texlog.Text = string.Format("{0}\r\n{1}", tex, texlog.Text);
            }
            //this.texlog.Text = string.Format("{0}\r\n{1}", tex, texlog.Text);
        }//



        private void butstart_Click(object sender, EventArgs e)
        {
            //客户端连接服务器端
            //1创建Socket对象
            Socket socket = new Socket
                (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


            clientsocket = socket;

            //2连接服务器
            try
            {
                socket.Connect(IPAddress.Parse(texIP.Text), int.Parse(textport.Text));
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接失败，重新连接！");
                //Thread.Sleep(500);
                //butstart_Click(this, e);
                //MessageBox.Show(ex.ToString());
                return;
            }
            //3发送消息，接收消息
            Thread thread = new Thread(new ParameterizedThreadStart(ReceiveDate));
            thread.IsBackground = true;
            thread.Start(clientsocket);
        }//

        public void butsendMsg_Click(object sender, EventArgs e)
        {
            int Pass = FriendsState.Text.IndexOf("不在线");

            if (FriendsState.Text == "未建立会话")
            {
                MessageBox.Show("请先建立会话!");
            }
            else if (Pass != -1)
            {
                MessageBox.Show("对方不在线，无法发起会话！");
            }
            else if (clientsocket.Connected)
            {
                if (texMsg.Text != "")
                {
                    byte[] data = Encoding.Default.GetBytes(texMsg.Text);
                    clientsocket.Send(data, 0, data.Length, SocketFlags.None);
                    texlog.Text += (texMsg.Text + "   ：Me" + "\r\n\r\n");
                    texMsg.Text = "";
                }
                else
                {
                    MessageBox.Show("发送的信息不能为空！");
                }

            }
        }//

        private void UserFrom_FormClosed(object sender, FormClosedEventArgs e)//
        {
            //判断是否已连接,如果已连接那么就关闭连接
            StopContent();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            AddMyFriends myFriends = new AddMyFriends();
            myFriends.ShowDialog();
        }//

        public void UserFrom_Load(object sender, EventArgs e)
        {
            //显示主菜单和下拉菜单的用户昵称

            //用户姓名在容器中居中
            base.OnResize(e);
            int x = (int)(0.5 * (LinkState.Width - FriendsState.Width));
            int y = FriendsState.Location.Y;
            FriendsState.Location = new System.Drawing.Point(x, y);

            //Button button = new Button();
            //panel3.ControlAdded(button);


            //设置子窗体在容器里的方法
            LoginHome.masterForm.Dock = DockStyle.Fill;
            LoginHome.masterForm.TopLevel = false;
            ServiceSide.Controls.Clear();//清除容器
            LoginHome.masterForm.Parent = this.ServiceSide;
            ServiceSide.Controls.Add(LoginHome.masterForm);
            LoginHome.masterForm.Show();

            //添加该用户好友
            var DML = string.Format("select * from MyFriends mf,Users u where mf.MyfriendID = u.UserID and mf.UserID = {0}", ThisMyInfo.UserID);
            SqlDataReader reader = DBHelps.Select(DML);
            int i = 0;
            while (reader.Read())
            {
                friend = new Button();
                this.Controls.Add(friend);
                FriendsList.Controls.Add(friend);
                friend.Dock = DockStyle.Top;
                friend.Width = 219;
                friend.Height = 50;
                friend.Text = reader["UserName"].ToString();
                friend.BackColor = Color.Transparent;
                friend.FlatStyle = FlatStyle.Flat;

                button[i] = friend.Text;
                i++;
                friend.Click += Friend_Click;
            }
            reader.Close();
            DBHelps.reader = null;
        }


        public static Button friend = null;//

        public static string MyFriendsName = null;//

        string[] button = new string[10];//
        private void Friend_Click(object sender, EventArgs e)
        {
            string send = sender.ToString();
            string username = send.Substring(35);
            bool resu = false;
            for (int i = 0; i < button.Length; i++)
            {
                if (button[i] == username)
                {
                    var DML = string.Format("select ThisIP from Users where UserName='{0}'", button[i]);
                    SqlDataReader reader = DBHelps.Select(DML);
                    if (reader.Read())
                    {
                        if (reader["ThisIP"].ToString() == "")
                        {
                            FriendsState.Text = (button[i] + "(不在线)");
                        }
                        else
                        {
                            texIP.Text = reader["ThisIP"].ToString();
                            butstart_Click(sender, e);
                            FriendsState.Text = (button[i] + "(在线)");
                            resu = true;
                        }
                    }
                    reader.Close();
                    DBHelps.reader = null;
                    if (resu)
                    {
                        var DML2 = string.Format("select UserID from Users where UserName='{0}'", button[i]);
                        SqlDataReader reader2 = DBHelps.Select(DML2);
                        if (reader2.Read())
                        {
                            MyFriendsName = reader2["UserID"].ToString();
                        }
                        reader2.Close();
                        DBHelps.reader = null;
                    }
                    break;
                }
            }
        }//

        private void button8_Click(object sender, EventArgs e)
        {
            var DML = string.Format("update Users set ThisIP=null where UserID = {0}", ThisMyInfo.UserID);
            DBHelps.Command(DML);
            Environment.Exit(0);
        }//

        private void button9_Click(object sender, EventArgs e)
        {
            Client.userFrom.Hide();
            Client client = new Client();
            client.ShowDialog();
            Client.userFrom.Close();
        }//

        private void UserFrom_FormClosing(object sender, FormClosingEventArgs e)
        {
            //判断是否已连接,如果已连接那么就关闭连接
            StopContent();
        }


        //无边框拖动窗体-----------------------------------------------
        [DllImport("user32.dll")]//*********************拖动无窗体的控件  需要引用
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int W = 0x0112;
        public const int S = 0xF010;
        public const int H = 0x0002;
        private void UserFrom_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(this.Handle, W, S + H, 0);//*********************调用移动无窗体控件函数
        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }



        private void button1_Click(object sender, EventArgs e)
        {
            int Pass = FriendsState.Text.IndexOf("不在线");
            if (Pass!=-1)
            {
                MessageBox.Show("用户不在线,无法分享文件！");
            }
            else
            {
                ShareFile shareFile = new ShareFile(MyFriendsName);
                shareFile.Show();
            }
        }//

        private void texlog_TextChanged(object sender, EventArgs e)
        {

        }

        private void mini_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void texMsg_TextChanged(object sender, EventArgs e)
        {

        }

        private void panel5_Paint(object sender, PaintEventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {

        }
    }
}
